package com.qf.controller;

import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author 86181
 * @Date 2022/9/13 14:40
 * @Version 1.0
 **/
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;

    //访问页面
    @RequestMapping("/{page}")
    public String page(@PathVariable("page") String page) {
        System.out.println(page);

        return page;
    }

    @RequestMapping("/findAll")
    public ModelAndView findAll() {
        ModelAndView modelAndView = new ModelAndView();
        List<User> all = userService.findAllUser();
        modelAndView.setViewName("list");
        modelAndView.addObject("users", all);
        return modelAndView;
    }

    @RequestMapping("login")
    public String login(User user, HttpSession httpSession) {
        Boolean login = userService.login(user, httpSession);
        if (login) {
            return "redirect:/user/findAll";
        } else {
            return "index";
        }
    }

    @RequestMapping("deleteUser")
    public String deleteUser(int id) {
        int i = userService.deleteUser(id);
        return "redirect:/user/findAll";
    }

    @GetMapping("addUser")
//    @ResponseBody
    public String addUser(User user) {
        int i = userService.addUser(user);
        if (i > -1) {
            System.out.println(i);
            return "redirect:/user/findAll";
        }
        return "error";
    }

    @RequestMapping("findById")
    public String findById(int id, Model model) {
        User byId = userService.findUserById(id);
        System.out.println(byId);
        model.addAttribute("findId", byId);
        return "update";
    }

    @RequestMapping(value = "updateUser", method = RequestMethod.POST)

    public String updateUser(User user, HttpServletRequest req) {
        int i = userService.updateUser(user);
        if (i > -1) {
            return "redirect:/user/findAll";
        }
        return "error";
    }
}